package ee.subjects.frontend.controller.command.personCommands;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.google.gson.Gson;

import ee.subjects.backend.model.data.Person;
import ee.subjects.backend.services.PersonService;
import ee.subjects.backend.services.PersonServiceImpl;
import ee.subjects.frontend.controller.command.Command;

public class AjaxPersonCommands implements Command {
	


	@Override
	public int execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String ajaxTask = "undefined";
		
		if(request.getParameter("ajaxTask") != null){
			ajaxTask=request.getParameter("ajaxTask");
		}
		
		if(ajaxTask.equals("get_person_by_letter_overlap")){
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.print(this.getPersonsByOverlapLetters(request));
		}
		
		return 0;
	}


	private String getPersonsByOverlapLetters(HttpServletRequest request) {
		String overlapLetters = "";
		if(request.getParameter("letters") != null){
			overlapLetters=request.getParameter("letters");
			
			PersonService personService = new PersonServiceImpl();
			List<Person> personsList = personService.getPersonsByFullName(overlapLetters);
			
			
			Gson gson = new Gson();
	        String json = gson.toJson(personsList);
	        System.out.println(json);
			return json;
			
		}
		return "";
	}

}
